package com.himiotech.core.project.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.himiotech.core.project.data.mapper.LoginInfoMapper;
import com.himiotech.core.project.model.entity.LoginInfo;
import com.himiotech.core.project.model.metadata.LoginInfoMetadata;
import com.himiotech.core.project.service.ILoginInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 系统访问日志情况信息 服务层处理
 *
 * @author ruoyi
 * @author wuwenbin
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class LoginInfoServiceImpl extends ServiceImpl<LoginInfoMapper, LoginInfo> implements ILoginInfoService {

    @Autowired
    private LoginInfoMapper loginInfoMapper;

    /**
     * 查询分页数据
     *
     * @param page      分页信息
     * @param loginInfo 业务信息查询条件
     * @return 分页对象及数据
     */
    @Override
    public Page<LoginInfo> selectLoginInfoListPage(Page<LoginInfo> page, LoginInfo loginInfo) {
        QueryWrapper<LoginInfo> query = Wrappers.query();
        query.like(ObjectUtil.isNotEmpty(loginInfo.getLoginName()), LoginInfoMetadata.LOGIN_NAME.getColName(), loginInfo.getLoginName());
        query.eq(ObjectUtil.isNotEmpty(loginInfo.getLoginLocation()), LoginInfoMetadata.LOGIN_LOCATION.getColName(), loginInfo.getLoginLocation());
        query.eq(ObjectUtil.isNotEmpty(loginInfo.getStatus()), LoginInfoMetadata.STATUS.getColName(), loginInfo.getStatus());
        Map<String, Object> searchParams = loginInfo.getSearchParams();
        if (!searchParams.isEmpty()) {
            String loginTimeStart = MapUtil.getStr(searchParams, StrUtil.toCamelCase(LoginInfoMetadata.LOGIN_TIME.getColName()).concat("Start")).concat(" 00:00:00");
            query.ge(StrUtil.isNotEmpty(loginTimeStart), LoginInfoMetadata.LOGIN_TIME.getColName(), loginTimeStart);
            String loginTimeEnd = MapUtil.getStr(searchParams, StrUtil.toCamelCase(LoginInfoMetadata.LOGIN_TIME.getColName()).concat("End")).concat(" 23:59:59");
            query.le(StrUtil.isNotEmpty(loginTimeEnd), LoginInfoMetadata.LOGIN_TIME.getColName(), loginTimeEnd);
        }

        page = loginInfoMapper.selectPage(page, query);
        return page;
    }

    /**
     * 清空系统登录日志
     */
    @Override
    public void cleanLoginInfo() {
        loginInfoMapper.cleanLoginInfo();
    }
}
